# -*- coding: utf-8 -*-

"""
@Datetime: 2019/1/31
@Author: Zhang Yafei
"""
import re
from application import app
from common.models.models import User
from flask import request, redirect, g, session
from common.libs.UserService import UserService
from common.libs.UrlManager import UrlManager
from common.libs.LogService import LogService


@app.before_request
def before_request():
    ignore_urls = app.config['IGNORE_URLS']
    ignore_check_login_urls = app.config['IGNORE_CHECK_LOGIN_URLS']
    path = request.path
    pattern = re.compile('|'.join(ignore_check_login_urls))
    if pattern.match(path):
        return

    pattern = re.compile('|'.join(ignore_urls))
    if pattern.match(path):
        return

    user_info = check_login()

    g.current_user = None
    if user_info:
        g.current_user = user_info

    # 加入日志
    LogService.addAccessLog()
    if not user_info:
        return redirect(UrlManager.buildUrl('/account/login'))


def check_login():
    """检查登录"""
    cookies = request.cookies
    auth_cookie = cookies[app.config['AUTH_COOKIE_NAME']] if app.config['AUTH_COOKIE_NAME'] in cookies else ''
    if auth_cookie is None:
        return False
    auth_info = auth_cookie.split('#')
    if len(auth_info) != 2:
        return False
    try:
        user_info = User.query.filter_by(id=auth_info[1]).first()
    except Exception as e:
        return False

    if user_info is None:
        return False

    if auth_info[0] != UserService.genAuthCode(user_info):
        return False

    if user_info.status != 1:
        return False

    return user_info